package com.zyasdk.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;

public class CurrRunApp {
	/** first app user */
	public static final int AID_APP = 10000;
	/** offset for uid ranges for each user */
	public static final int AID_USER = 100000;

	/**
	 * 获取当前打开的应用包名
	 * 
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public static String getForegroundApp(Context context) {
		try {
			// 如果系统为5.0以下则直接调用系统提供的方法返回当前打开的应用
			if (Build.VERSION.SDK_INT <= 20) {
				return getActivePackagesCompat(context);
			}
			// 以下是5.0系统以上获取当前打开的应用的方法。
			File[] files = new File("/proc").listFiles();
			int lowestOomScore = Integer.MAX_VALUE;
			String foregroundProcess = null;
			for (File file : files) {
				if (!file.isDirectory()) {
					continue;
				}
				int pid;
				try {
					pid = Integer.parseInt(file.getName());
				} catch (NumberFormatException e) {
					continue;
				}
				try {
					String cgroup = read(String.format("/proc/%d/cgroup", pid));
					String[] lines = cgroup.split("\n");
					String cpuSubsystem = null;
					String cpuaccctSubsystem = null;

					// 取出cpu和cpuacct的值
					for (String str : lines) {
						if (str.indexOf(":cpu:") > 0)
							cpuSubsystem = str;
						if (str.indexOf(":cpuacct:") > 0)
							cpuaccctSubsystem = str;
					}
					if (cpuSubsystem == null || cpuaccctSubsystem == null)
						continue;

					if (!cpuaccctSubsystem.endsWith(Integer.toString(pid))) {
						// not an application process
						continue;
					}
					if (cpuSubsystem.endsWith("bg_non_interactive")) {
						// background policy
						continue;
					}
					String cmdline = read(String
							.format("/proc/%d/cmdline", pid));
					if (cmdline.contains("com.android.systemui")) {
						continue;
					}
					int uid = Integer.parseInt(cpuaccctSubsystem.split(":")[2]
							.split("/")[1].replace("uid_", ""));
					if (uid >= 1000 && uid <= 1038) {
						// system process
						continue;
					}
					int appId = uid - AID_APP;
					// loop until we get the correct user id.
					// 100000 is the offset for each user.
					while (appId > AID_USER) {
						appId -= AID_USER;
					}
					if (appId < 0) {
						continue;
					}
					File oomScoreAdj = new File(String.format(
							"/proc/%d/oom_score_adj", pid));
					if (oomScoreAdj.canRead()) {
						int oomAdj = Integer.parseInt(read(oomScoreAdj
								.getAbsolutePath()));
						if (oomAdj != 0) {
							continue;
						}
					}
					int oomscore = Integer.parseInt(read(String.format(
							"/proc/%d/oom_score", pid)));
					if (oomscore < lowestOomScore) {
						lowestOomScore = oomscore;
						foregroundProcess = cmdline;
					}
				} catch (IOException e) {
				}
			}
			return foregroundProcess;
		} catch (Exception e) {
			return null;
		}
	}

	private static String read(String path) throws IOException {
		try {
			StringBuilder output = new StringBuilder();
			BufferedReader reader = new BufferedReader(new FileReader(path));
			output.append(reader.readLine());
			for (String line = reader.readLine(); line != null; line = reader
					.readLine()) {
				output.append('\n').append(line);
			}
			reader.close();
			return output.toString().trim();// 不调用trim()，包名后面会带有乱码
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取当前运行的应用包名（5.0以上不可用）
	 * 
	 * @return
	 */
	private static String getActivePackagesCompat(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		final List<ActivityManager.RunningTaskInfo> taskInfo = activityManager
				.getRunningTasks(1);
		final ComponentName componentName = taskInfo.get(0).topActivity;
		return componentName.getPackageName();
	}

}
